package org.example.c_0_003;

import org.junit.Test;

import java.util.ArrayList;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 只有await的线程数量达到指定数量，才会放行。
 */
public class T_CyclicBarrier {
    private CyclicBarrier cyclicBarrier = new CyclicBarrier(20,()-> System.out.println(Thread.currentThread().getName()+"放行"));

    private void m(){
        System.out.println(Thread.currentThread().getName()+"执行m方法开始");
        try {
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"执行m方法结束");
    }

    @Test
    public void run(){
        ArrayList<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            threads.add(new Thread(this::m,i+""));
        }
        threads.forEach(obj -> obj.start());
        threads.forEach(obj -> {
            try {
                obj.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
